import cv2  
import time
import pyzbar.pyzbar as pyzbar
import numpy as np

# 裁剪
# 宽度是x 顶点向右方向  高度是y ,顶点向下方向
crop_x_min = 0   
crop_x_max = 1000
crop_y_min = 590   
crop_y_max = 1890

class frameClass:

    def QR_test(self,img):
        # 使用pyzbar解析二维码图片内容
        barcodes = pyzbar.decode(img)
        print(f"borcodes is {barcodes}")
        if barcodes:
            for barcode in barcodes:
                # 提取条形码的边界框的位置
                # 画出图像中条形码的边界框
                (x, y, w, h) = barcode.rect
                cv2.rectangle(self.frame, (x, y), (x + w, y + h), (0, 255, 255), 3)
        
                # 条形码数据为字节对象，所以如果我们想在输出图像上画出来，就需要先将它转换成字符串  类型也直接识别出来了
                barcodeData = barcode.data.decode("utf-8")
                barcodeType = barcode.type
               
                center_x = int(x+w/2)
                center_y = int(y+h/2)
                feature = [center_x,center_y,0]
                print(f"target pixel center is {feature}")

                # 绘出图像上条形码的数据和条形码类型
                text = "{} ({})".format(barcodeData, barcodeType)
                cv2.putText(self.frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,.5, (0, 0, 125), 2)     

    def run(self,):
        #### 通过CV库函数获取视频流数据
        cap = cv2.VideoCapture(9,)
        cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))  

        while True:  
            ret, self.frame = cap.read()  
            if not ret:
                time.sleep(0.1)
                #### 图像一旦获取失败，不断循环获取图像
                cap = cv2.VideoCapture(9,)
                cap.set(cv2.CAP_PROP_FOURCC,cv2.VideoWriter_fourcc('M','J','P','G'))  
                print("Can't to capture from camera. Exiting ...")  
                break  
            
            #### 图像裁剪--感兴趣区域进行检测
            crop = np.zeros([1944,2592,3],np.uint8)
            crop[crop_x_min:crop_x_max,crop_y_min:crop_y_max] = self.frame[crop_x_min:crop_x_max,crop_y_min:crop_y_max]
            img = crop
            
            #### 二维码检测
            self.QR_test(img)
            time.sleep(0.01)
            
            #### 图像显示与保存
            cv2.imshow('frame', self.frame)
            cv2.imwrite(f"crop.png",img)
            cv2.imwrite(f"frame.png",self.frame)
        
            # 按下'q'键退出循环  
            if cv2.waitKey(1) & 0xFF == ord('q'):  
                break  

        # 释放摄像头资源  
        cap.release()  
        # 关闭所有OpenCV窗口  
        cv2.destroyAllWindows()

a = frameClass()
a.run()